package com.rzico.sbl.ui.report

import android.widget.ImageView
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzg.extend.jackson.JsonUtil
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportOrderDetailBinding
import com.rzico.sbl.model.OrderGoods
import com.rzico.sbl.model.OrderLogData
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.report.dispatch.ReportDispatchLookActivity
import com.rzico.sbl.ui.report.driver.DriverStationBarrelActivity
import com.rzico.sbl.ui.report.driver.DriverStationMoneyActivity
import com.rzico.sbl.ui.report.other.ReportService
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.ui.report_0537.QFOrderConfirmActivity
import com.rzico.sbl.viewmodel.ReportViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.copyStringToClip
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.view.FullyLinearLayoutManager
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showBottomPhoneDialog
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONArray
import org.json.JSONObject

class ReportOrderDetailActivity : BaseActivity(R.layout.activity_report_order_detail) {

    private val mBinding by lazy { ActivityReportOrderDetailBinding.bind(getRootView()) }

    private val mLogList = arrayListOf<OrderLogData>()
    private var mEnterpriseId = ""
    private var mOrderSn = ""
    private var mOrderStatus = ""
    private var mOrderAmount = ""
    private var mCreateDate = ""
    private var mShipId = ""
    private var mShippingSn = ""
    private var mReceivePhone = ""
    private var mReceiveAdress = ""

    override fun getViewModel() = get<ReportViewModel>()

    override fun initData() {
        initTitle(
            title = intent.getExtra("title")
                .isEmpty()
                .conditionElseValue(
                    actionTrue = { "订单详情" },
                    actionFalse = { "运单详情" }
                )
        )

        initLayout()

        getData()
    }

    private fun initLayout() {
        mBinding.detailList.apply {
            isNestedScrollingEnabled = false
            layoutManager = FullyLinearLayoutManager(getIContext())

            addItemDecoration(
                SpaceTBDecoration(
                    top = 5f,
                    hasHeader = false,
                    hasFooter = false,
                    spaceColor = R.color.white
                )
            )

            mAdapter = SlimAdapter.creator()
                .register<OrderGoods>(R.layout.item_order_detail_list) { jector, bean, _ ->
                    jector.apply {
                        text(R.id.item_order_name, bean.name)
                        text(R.id.item_order_type, "规格: ${bean.spec.orEmpty()}")
                        text(R.id.item_order_price, "单价: ${bean.price.formatDecimal()}元")
                        text(R.id.item_order_num, "x${bean.quantity}")

                        with<ImageView>(R.id.item_order_img) {
                            it.loadImage(bean.thumbnail)
                        }
                    }
                }
                .attachTo(this)
        }
    }

    override fun initListener() {
        mBinding.apply {
            detailLogLl.oneClick {
                mLogList.notEmpty {
                    showOrderLogDialog(this)
                }
            }

            detailMoneyLl.oneClick {
                mEnterpriseId.notEmpty {
                    startActivityEx<DriverStationMoneyActivity>(
                        "mode" to "hide",
                        "shopId" to this
                    )
                }
            }

            detailBarrelLl.oneClick {
                mEnterpriseId.notEmpty {
                    startActivityEx<DriverStationBarrelActivity>(
                        "mode" to "hide",
                        "shopId" to this
                    )
                }
            }

            detailCall.oneClick {
                mReceivePhone.notEmpty {
                    showBottomPhoneDialog(this)
                }
            }

            detailAdress.longClick {
                mReceiveAdress.notEmpty {
                    copyStringToClip(this)
                    showToast("地址复制成功！")
                }
            }

            detailAdressCopy.oneClick {
                mReceiveAdress.notEmpty {
                    copyStringToClip(this)
                    showToast("地址复制成功！")
                }
            }

            detailFeeAll.oneClick {
                it.gone()
                detailFeeExpand.expand()
            }

            detailDispatch.oneClick {
                (mShipId.isNotEmpty() && mShippingSn.isNotEmpty())
                    .condition {
                        startActivityEx<ReportDispatchLookActivity>(
                            "shipId" to mShipId,
                            "orderSn" to mOrderSn,
                            "shippingSn" to mShippingSn
                        )
                    }
            }

            detailNum.longClick {
                mOrderSn.notEmpty {
                    copyStringToClip(this)
                    showToast("订单编号复制成功！")
                }
            }

            detailNumCopy.oneClick {
                mOrderSn.notEmpty {
                    copyStringToClip(this)
                    showToast("订单编号复制成功！")
                }
            }

            detailBtn1.oneClick {
                mOrderSn.notEmpty {
                    when (serviceId) {
                        in ReportService.MODE_FINANCE -> {
                            startActivityEx<QFOrderConfirmActivity>(
                                "amount" to mOrderAmount.formatDecimal(),
                                "orderSn" to mOrderSn,
                                "time" to mCreateDate.getTimeString()
                            )
                        }
                        else -> {
                            showHintDialog(
                                title = "确认订单",
                                hint = "确定要审核订单吗？",
                                onSure = {
                                    getViewModel()
                                        .confirmOrder(this)
                                        .bindLifeCycle(getLifecycleOwner())
                                        .subscribeBySuccess(
                                            event = getViewModel(),
                                            onSuccess = {
                                                showToast("订单确认成功！")

                                                // 报货订单刷新
                                                LiveEventBus
                                                    .get("orderModify")
                                                    .post("confirm")

                                                finishView()
                                            }
                                        )
                                }
                            )
                        }
                    }
                }
            }

            detailBtn2.oneClick {
                mOrderSn.notEmpty {
                    showMemoDialog(
                        title = "订单驳回",
                        hint = "请输入驳回原因",
                        inputType = "longText",
                        canEmpty = false
                    ) {
                        getViewModel()
                            .requestBind(
                                isMultipart = true,
                                requestUrl = ReportUrl.getBaseUrl().rptDeliverRet,
                                params = arrayOf(
                                    "sn" to this,
                                    "memo" to it
                                )
                            )
                            .bindLifeCycle(getLifecycleOwner())
                            .subscribeBySuccess(
                                event = getViewModel(),
                                onSuccess = {
                                    showToast("订单驳回成功！")

                                    // 报货订单刷新
                                    LiveEventBus
                                        .get("orderModify")
                                        .post("confirm")

                                    finishView()
                                }
                            )
                    }
                }
            }
        }
    }

    /**
     * 订单详情
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .orderDetail(intent.getExtra("orderSn"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val obj = JSONObject(result)

                    mEnterpriseId = obj.optNotNull("enterpriseId")
                    mOrderSn = obj.optNotNull("sn")
                    mOrderStatus = obj.optNotNull("status")
                    mOrderAmount = obj.optNotNull("amountPayable")
                    mCreateDate = obj.optNotNull("createDate")
                    mShipId = obj.optNotNull("shippingId")
                    mShippingSn = obj.optNotNull("shippingSn")
                    val freightMemo = obj.optNotNull("freightMemo")
                    val freightPaid = obj.optNotNull("freightPaid")
                    val freightUnpaid = obj.optNotNull("freightPayable")

                    mBinding.apply {
                        detailBottom.isVisible = (
                                intent.getExtra("mode") == "confirm"
                                        && mOrderStatus in "unpaid,rejected")
                        detailBtn2.isVisible = (userRole == "5" && mOrderStatus == "unpaid")

                        detailTotal.text = obj.optNotNull("quantity")
                        detailAmount.text = obj.optNotNull("price").formatDecimal()

                        // 商品小计
                        obj.optNotNull("memo").apply {
                            val items = split("|")
                            detailHint.text = items[0]
                                .replace(";\n", ";")
                                .replace(";", ";\n")

                            (items.size > 1).condition {
                                detailMai.text =
                                    items[1].notEmpty { detailMaiLl.visible() }
                            }
                        }
                        // 代金券(一)
                        obj.optNotNull("couponDiscount")
                            .also {
                                (it.intValue != 0)
                                    .condition {
                                        detailCoupon1Ll.visible()
                                        detailCoupon1.text =
                                            "–${(it.intValue * 0.3).formatDecimal()}元 ($it * 0.3)"
                                    }
                            }
                        // 代金券(二)
                        obj.optNotNull("vipDiscount")
                            .also {
                                (it.intValue != 0)
                                    .condition {
                                        detailCoupon2Ll.visible()
                                        detailCoupon2.text =
                                            "–${(it.intValue * 0.3).formatDecimal()}元 ($it * 0.3)"
                                    }
                            }
                        // 代金券(三)
                        obj.optNotNull("exchangeDiscount")
                            .also {
                                (it.intValue != 0)
                                    .condition {
                                        detailCoupon3Ll.visible()
                                        detailCoupon3.text =
                                            "–${(it.intValue * 2.0).formatDecimal()}元 ($it * 2.0)"
                                    }
                            }
                        // 运费
                        obj.optNotNull("freight")
                            .also {
                                (freightPaid.doubleValue == 0.0
                                        && freightUnpaid.doubleValue == 0.0
                                        && it.doubleValue > 0)
                                    .condition {
                                        detailFee1Ll.gone()
                                        detailFeeLl.visible()
                                        detailFee.text = "+${it.formatDecimal()} 元"
                                    }
                            }
                        // 重量合计
                        detailWeight.text = "${
                            obj.optNotNull("weight")
                                .also {
                                    detailWeightLl.isVisible = it.doubleValue > 0
                                }
                        } kg"
                        // 货款合计
                        detailPrice.text = "${obj.optNotNull("amountPayable").formatDecimal()} 元"

                        // 曲阜实付、记账金额
                        (serviceId in ReportService.MODE_FINANCE)
                            .condition {
                                val amountPaid = obj.optNotNull("amountPaid").doubleValue
                                val amountOwe = obj.optNotNull("arrears").doubleValue

                                detailPaidLl.isVisible = amountPaid > 0 || amountOwe > 0
                                detailPaid.text = amountPaid.formatDecimal()
                                detailOwe.text = amountOwe.formatDecimal()
                            }

                        // 运费明细
                        ((freightPaid.doubleValue > 0 || freightUnpaid.doubleValue > 0))
                            .condition {
                                detailFee1Ll.visible()
                                detailFeeLl.gone()
                                // 运费小计
                                detailFee1Hint.text =
                                    freightMemo
                                        .replace(";\n", ";")
                                        .replace(";", ";\n")
                                // 已付运费
                                detailFeePaid.text = "${freightPaid.formatDecimal()} 元"
                                // 未付运费
                                detailFeeUnpaid.text = "${freightUnpaid.formatDecimal()} 元"

                                // 是否含运费
                                // val isFreight = obj.optBoolean("isFreight")
                                // detailAppend.text =
                                //     when {
                                //         serviceId in ReportService.FEE_CONTROL && isFreight -> " (含运费)"
                                //         serviceId in ReportService.FEE_CONTROL && !isFreight -> " (不含运费)"
                                //         else -> ""
                                //     }
                            }

                        /*---------------------- 客户信息 ----------------------*/
                        val objReceive = obj.optJSONObject("receiver") ?: JSONObject()
                        mReceivePhone = objReceive.optNotNull("phone")
                        mReceiveAdress = objReceive.optNotNull("address")
                        // 姓名
                        detailName.text = objReceive.optNotNull("consignee")
                        // 电话
                        detailPhone.text = mReceivePhone
                        // 收货地址
                        detailAdress.text = mReceiveAdress
                        // 买家欠款
                        detailMoney.text =
                            obj.optNotNull("arrearsSum")
                                .also {
                                    detailMoneyLl.isVisible = it.doubleValue != 0.0
                                }.formatDecimal()
                        // 买家欠桶
                        detailBarrel.text =
                            obj.optNotEmpty("borrowSum", "0")
                                .also {
                                    detailBarrelLl.isVisible = it.intValue != 0
                                }
                        // 空桶抵扣
                        detailStore.text =
                            obj.optNotNull("adAdvanceStock")
                                .also {
                                    detailStoreLl.isVisible = it.intValue > 0
                                }


                        /*---------------------- 订单信息 ----------------------*/
                        // 订单状态
                        detailStatus.text = obj.optNotNull("statusDescr")
                        // 订单编号
                        detailNum.text = mOrderSn
                        // 支付方式
                        detailPay.text =
                            obj.optNotNull("paymentMethod")
                                .notEmpty { detailPayLl.visible() }
                        // 销售站点
                        detailShou.text =
                            obj.optNotNull("sellerName")
                                .notEmpty { detailShouLl.visible() }
                        // 下单时间
                        detailCreate.text =
                            obj.optNotNull("createDate")
                                .getTimeString()
                        // 预约时间
                        detailYue.text =
                            obj.optNotNull("hopeDate")
                                .notEmpty { detailYueLl.visible() }
                                .getTimeString()
                        // 发货时间
                        detailFa.text =
                            obj.optNotNull("shippingDate")
                                .notEmpty { detailFaLl.visible() }
                                .getTimeString()
                        // 送达时间
                        detailDa.text =
                            obj.optNotNull("deliveryDate")
                                .notEmpty { detailDaLl.visible() }
                                .getTimeString()
                        // 交易完成
                        detailWan.text =
                            obj.optNotNull("completeDate")
                                .notEmpty { detailWanLl.visible() }
                                .getTimeString()
                        // 送达明细
                        when (serviceStep) {
                            "2", "3" -> detailDispatch.isVisible = mOrderStatus == "completed"
                        }
                        // 派单留言
                        detailPai.text =
                            obj.optNotNull("shippingMemo")
                                .trimEnd('\n')
                                .notEmpty { detailPaiLl.visible() }
                        // 配送方式
                        detailDeliver.text =
                            obj.optNotNull("shippingMethod")
                                .notEmpty { detailDeliverLl.visible() }
                        // 配送站点
                        detailZhan.text =
                            obj.optNotNull("shopName")
                                .notEmpty { detailZhanLl.visible() }
                        // 配送人员
                        detailRen.text =
                            obj.optNotNull("adminName")
                                .notEmpty { detailRenLl.visible() }

                        /*---------------------- 订单状态 ----------------------*/
                        val objLog = obj.optJSONArray("orderLogs") ?: JSONArray()
                        mLogList.apply {
                            clear()
                            addItems(
                                JsonUtil.toList<OrderLogData>(
                                    objLog.toString(),
                                    OrderLogData::class.java
                                ).reversed()
                            )
                        }
                        detailLog1.text = mLogList[0].createDate.getTimeString()
                        detailLog2.text = mLogList[0].content
                    }

                    /*---------------------- 商品信息 ----------------------*/
                    val objOrder = obj.optJSONArray("orderItems") ?: JSONArray()
                    mList.clear()
                    mList.addItems(
                        JsonUtil.toList(
                            objOrder.toString(),
                            OrderGoods::class.java
                        )
                    )
                    mAdapter.setDataList(mList)
                }
            )
    }

}